/*
 *  Others.cpp
 *  T3nsors
 *
 *  Created by Michael Barriault on 10-09-23.
 *  Copyright 2010 MikBarr Studios. All rights reserved.
 *
 */

#include <T3nsors/Others.h>
#include <T3nsors/Macros.h>
#include <cstdlib>
#include <sys/time.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>

string itos(long long i) {
	std::ostringstream str;
	str << i;
	return str.str();
}

string ftos(real i) {
	std::ostringstream str;
	str << i;
	return str.str();
}

int stoi(string str) {
	std::istringstream istr(str);
	int i;
	istr >> i;
	return i;
}

real stof(string str) {
	std::istringstream istr(str);
	real i;
	istr >> i;
	return i;
}

std::vector<std::string> ArgToVec(int argc, char*const argv[]) {
	std::vector<std::string> A;
	FOR(i,argc-1)
		A.push_back((std::string)argv[i+1]);
	return A;
}

void Alloc_Error(string id) {
	std::cout << "Allocation error making " << id << std::endl;
}

void print(string str, bool fl) {
#ifdef DEBUG
	std::cout << str << std::flush;
	if ( not fl ) std::cout << std::endl;
#endif
}

struct timeval gettime() {
	struct timeval now;
	struct timezone tzp;
	gettimeofday(&now, &tzp);
	return now;
}

string timer(struct timeval before, int mult) {
	std::ostringstream str;
	struct timezone tzp;
	struct timeval now,lapsed;
	gettimeofday(&now,&tzp);
	if ( before.tv_usec > now.tv_usec ) {
		now.tv_usec += 1000000;
		now.tv_sec--;
	}
	lapsed.tv_usec = now.tv_usec - before.tv_usec;
	lapsed.tv_sec = now.tv_sec - before.tv_sec;
	int left = int(mult*(lapsed.tv_sec+real(lapsed.tv_usec)/1E6));
	if ( left > 3600 )
		str << left/3600 << "h ";
	if ( left > 60 )
		str << (left%3600)/60 << "m ";
	str << left%60 << "s" << std::flush;
	return str.str();
}

string bytes(long long int b) {
	char pre[10] = "BKMGTPEZY";
	int i=0;
	string rd = "";
	int rem;
	do {
		rem = b%1024;
		rd = itos(rem) + pre[i] + " " + rd;
		b = (b - rem)/1024;
		i++;
	} while ( b > 0);
	return rd;
}

real smoother(real x, real x0) {
	if ( fabs(x) < fabs(x0) )
		return pow(pow(x,2)-pow(x0,2),4)/pow(x0,8);
	return 0.;
}

real dsmoother(real x, real x0) {
	if ( fabs(x) < fabs(x0) )
		return 8*x*pow(pow(x,2)-pow(x0,2),3)/pow(x0,8);
	return 0.;
}

real d2smoother(real x, real x0) {
	if ( fabs(x) < fabs(x0) )
		return 8*pow(pow(x,2)-pow(x0,2),2)*(7*pow(x,2)-pow(x0,2))/pow(x0,8);
	return 0.;
}

int step(real x) {
	if ( x >= 0 ) return 1;
	else return 0;
}

string mkdir(string id) {
	return (std::string)"mkdir " + id + " 2> /dev/null";
}

string cd(string id) {
	return (std::string)"cd " + id;
}

string timecoord() {
	time_t now;
	struct tm *timeinfo;
	time(&now);
	timeinfo = localtime(&now);
	char str[12];
	strftime(str,9,"%U%w%H%M",timeinfo);
	return (string)str;
}

real PM(int i, int I) {
	return 1 - 2*i/(I-1);
}
